package phone.qyg.com.qyg.activity;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.app.base.tool.BaseActivity;
import com.app.config.ApplicationConfig;
import com.app.utils.CommonUtil;
import com.app.utils.SystemPrintl;
import com.app.view.view.SonicRuntimeImpl;
import com.app.view.view.SonicSessionClientImpl;
import com.tencent.sonic.sdk.SonicConfig;
import com.tencent.sonic.sdk.SonicEngine;
import com.tencent.sonic.sdk.SonicSession;
import com.tencent.sonic.sdk.SonicSessionConfig;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.CharacterRun;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.hwpf.usermodel.Table;
import org.apache.poi.hwpf.usermodel.TableCell;
import org.apache.poi.hwpf.usermodel.TableIterator;
import org.apache.poi.hwpf.usermodel.TableRow;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import phone.qyg.com.qyg.R;
import phone.qyg.com.qyg.model.Base;

//import org.apache.poi.hwpf.usermodel.CharacterRun;

//import org.apache.poi.hwpf.usermodel.CharacterRun;

/**
 * 作者：lblbh on 2018/3/14 14:41
 * 邮箱：lanbuhan@163.com
 * 功能：打开word 文件
 */
@ContentView(R.layout.html_layout)
public class WordActivity extends BaseActivity {

    @ViewInject(R.id.back)
    TextView back;

    @ViewInject(R.id.web_view)
    WebView web_view;

    TableIterator tableIterator;

    HWPFDocument hwpf = null;

    Range range = null;

    List pictures;

    String htmlPath;

    String picturePath;

    FileOutputStream output;

    int presentPicture = 0;

    int screenWidth;

    String fixImgUrl;

    String title;

    String pathUrl;

    SonicSession sonicSession;

    SonicSessionClientImpl sonicSessionClient;

    @Override
    public void initSucessView() {

        Object obj = getTransModels();

        String url = null;

        if(obj instanceof Base){
            Base base = (Base) obj;
            url = base.url;
            title = base.title;
        }

        screenWidth = this.getWindowManager().getDefaultDisplay().getWidth() - 10;

        if (!isRequestStr(url)) return;

        if(url.contains(".docx") || url.endsWith(".DOCX")){
            initWebView(url);
        }else{
            //默认处理 doc DOC
            fileDownPath(url);
        }
//
//        pathUrl = ApplicationConfig.APP_OFFICE_HTMl + "http://47.92.95.44:92/atta/data/resource/resmaterial/file/2018/04/26/54f0e070-18bf-49b3-bd63-57b97ccf756a.docx";;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        back.setText(setAttributeText(title));
        web_view.loadUrl(pathUrl);
    }


    private void fileDownPath(String url){
        RequestParams params = new RequestParams(url);
        //自动为文件命名
        params.setAutoRename(false);
        File file = new File(CommonUtil.DOC_DIR);
        if (!file.exists()) {
            file.mkdirs();
        }
        params.setSaveFilePath(CommonUtil.DOC_DIR + File.separator +System.currentTimeMillis()+".docx");
        x.http().get(params, new Callback.ProgressCallback<File>() {
            @Override
            public void onSuccess(File result) {
                //apk下载完成后，调用系统的安装方法
                pathUrl = result.getPath();
                getRange();
                makeFile();
                readAndWrite();
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                SystemPrintl.systemPrintl("下载失败");
            }
            @Override
            public void onCancelled(CancelledException cex) {}
            @Override
            public void onFinished() {}
            //网络请求之前回调
            @Override
            public void onWaiting() {}
            //网络请求开始的时候回调
            @Override
            public void onStarted() {}
            //下载的时候不断回调的方法
            @Override
            public void onLoading(final long total, final long current, boolean isDownloading) {
                //当前进度和文件总大小
                SystemPrintl.systemPrintl("current-->>"+current);
            }
        });
    }

    private void getRange() {
        FileInputStream in = null;
        POIFSFileSystem pfs = null;
        try {
            in = new FileInputStream(pathUrl);
            pfs = new POIFSFileSystem(in);
            hwpf = new HWPFDocument(pfs);

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        range = hwpf.getRange();
//
        pictures = hwpf.getPicturesTable().getAllPictures();
//
        tableIterator = new TableIterator(range);

    }


    public void makeFile() {

        String sdStateString = android.os.Environment.getExternalStorageState();

        if (sdStateString.equals(android.os.Environment.MEDIA_MOUNTED)) {
            try {

                String path = CommonUtil.DOC_DIR + File.separator + "doc";

                // String temp = path + File.separator
                // +"loveReader"+File.separator + "doc.html";

                File dirFile = new File(path);
                if (!dirFile.exists()) {
                    dirFile.mkdirs();
                }

                File myFile = new File(path + File.separator + "doc.html");

                if (!myFile.exists()) {
                    myFile.createNewFile();
                }

                htmlPath = myFile.getAbsolutePath();
            } catch (Exception e) {

            }
        }
    }


    /**
     * word 转化为 html
     */
    public void readAndWrite() {

        try {
            File myFile = new File(htmlPath);
            output = new FileOutputStream(myFile);
            String utf = "<head><meta http-equiv='content-type' content='text/html;charset=utf-8'></head>";

            String head = "<html>" + utf + "<body>";
            String tagBegin = "<p>";
            String tagEnd = "</p>";

            output.write(head.getBytes());

            int numParagraphs = range.numParagraphs();

            for (int i = 0; i < numParagraphs; i++) {
                Paragraph p = range.getParagraph(i);

                if (p.isInTable()) {
                    int temp = i;
                    if (tableIterator.hasNext()) {
                        String tableBegin = "<table style=\"border-collapse:collapse\" border=1 bordercolor=\"black\">";
                        String tableEnd = "</table>";
                        String rowBegin = "<tr>";
                        String rowEnd = "</tr>";
                        String colBegin = "<td>";
                        String colEnd = "</td>";

                        Table table = tableIterator.next();

                        output.write(tableBegin.getBytes());

                        int rows = table.numRows();

                        for (int r = 0; r < rows; r++) {
                            output.write(rowBegin.getBytes());
                            TableRow row = table.getRow(r);
                            int cols = row.numCells();
                            int rowNumParagraphs = row.numParagraphs();
                            int colsNumParagraphs = 0;
                            for (int c = 0; c < cols; c++) {
                                output.write(colBegin.getBytes());
                                TableCell cell = row.getCell(c);
                                int max = temp + cell.numParagraphs();
                                colsNumParagraphs = colsNumParagraphs
                                        + cell.numParagraphs();
                                for (int cp = temp; cp < max; cp++) {
                                    Paragraph p1 = range.getParagraph(cp);
                                    output.write(tagBegin.getBytes());
                                    writeParagraphContent(p1);
                                    output.write(tagEnd.getBytes());
                                    temp++;
                                }
                                output.write(colEnd.getBytes());
                            }
                            int max1 = temp + rowNumParagraphs;
                            for (int m = temp + colsNumParagraphs; m < max1; m++) {
                                Paragraph p2 = range.getParagraph(m);
                                temp++;
                            }
                            output.write(rowEnd.getBytes());
                        }
                        output.write(tableEnd.getBytes());
                    }
                    i = temp;
                }

                else {
                    output.write(tagBegin.getBytes());
                    writeParagraphContent(p);
                    output.write(tagEnd.getBytes());
                }
            }
            String end = "</body></html>";
            output.write(end.getBytes());
            output.close();
        } catch (Exception e) {
            System.out.println("readAndWrite Exception");
        }finally{
            initWebView(htmlPath);
        }
    }

    public void writeParagraphContent(Paragraph paragraph) {
        Paragraph p = paragraph;
        int pnumCharacterRuns = p.numCharacterRuns();

        for (int j = 0; j < pnumCharacterRuns; j++) {

            CharacterRun run = p.getCharacterRun(j);

            if (run.getPicOffset() == 0 || run.getPicOffset() >= 1000) {
                if (presentPicture < pictures.size()) {
                    writePicture();
                }
            } else {
                try {
                    String text = run.text();
                    if (text.length() >= 2 && pnumCharacterRuns < 2) {
                        output.write(text.getBytes());
                    } else {
                        int size = run.getFontSize();
                        int color = run.getColor();
                        String fontSizeBegin = "<font size=\""
                                + decideSize(size) + "\">";
                        String fontColorBegin = "<font color=\""
                                + decideColor(color) + "\">";
                        String fontEnd = "</font>";
                        String boldBegin = "<b>";
                        String boldEnd = "</b>";
                        String islaBegin = "<i>";
                        String islaEnd = "</i>";

                        output.write(fontSizeBegin.getBytes());
                        output.write(fontColorBegin.getBytes());

                        if (run.isBold()) {
                            output.write(boldBegin.getBytes());
                        }
                        if (run.isItalic()) {
                            output.write(islaBegin.getBytes());
                        }

                        output.write(text.getBytes());

                        if (run.isBold()) {
                            output.write(boldEnd.getBytes());
                        }
                        if (run.isItalic()) {
                            output.write(islaEnd.getBytes());
                        }
                        output.write(fontEnd.getBytes());
                        output.write(fontEnd.getBytes());
                    }
                } catch (Exception e) {
                    System.out.println("Write File Exception");
                }
            }
        }
    }

    /* word 转化为jpg*/
    public void writePicture() {
        Picture picture = (Picture) pictures.get(presentPicture);

        byte[] pictureBytes = picture.getContent();

        Bitmap bitmap = BitmapFactory.decodeByteArray(pictureBytes, 0,
                pictureBytes.length);

        makePictureFile();
        presentPicture++;

        File myPicture = new File(picturePath);

        try {

            FileOutputStream outputPicture = new FileOutputStream(myPicture);

            outputPicture.write(pictureBytes);

            outputPicture.close();
        } catch (Exception e) {
            System.out.println("outputPicture Exception");
        }

        String imageString = "<img src=\"" + picturePath + "\"";

        if (bitmap.getWidth() > screenWidth) {
            imageString = imageString + " " + "width=\"" + screenWidth + "\"";
        }
        imageString = imageString + ">";

        try {
            output.write(imageString.getBytes());
        } catch (Exception e) {
            System.out.println("output Exception");
        }
    }


    /*  */
    public void makePictureFile() {
        String sdString = android.os.Environment.getExternalStorageState();

        if (sdString.equals(android.os.Environment.MEDIA_MOUNTED)) {
            try {
                String picPath = CommonUtil.DOC_DIR + File.separator + "doc";

                File picDirFile = new File(picPath);

                if (!picDirFile.exists()) {
                    picDirFile.mkdirs();
                }
                File pictureFile = new File(picPath + File.separator
                        + presentPicture + ".jpg");

                if (!pictureFile.exists()) {
                    pictureFile.createNewFile();
                }

                picturePath = pictureFile.getAbsolutePath();

            } catch (Exception e) {
                System.out.println("PictureFile Catch Exception");
            }
        }
    }


    /**
     * word 转化为html 文字大小
     * @param size
     * @return
     */
    public int decideSize(int size) {

        if (size >= 1 && size <= 8) {
            return 1;
        }
        if (size >= 9 && size <= 11) {
            return 2;
        }
        if (size >= 12 && size <= 14) {
            return 3;
        }
        if (size >= 15 && size <= 19) {
            return 4;
        }
        if (size >= 20 && size <= 29) {
            return 5;
        }
        if (size >= 30 && size <= 39) {
            return 6;
        }
        if (size >= 40) {
            return 7;
        }
        return 3;
    }

    /**
     * word 转化 html 颜色
     * @param a
     * @return
     */
    private String decideColor(int a) {
        int color = a;
        switch (color) {
            case 1:
                return "#000000";
            case 2:
                return "#0000FF";
            case 3:
            case 4:
                return "#00FF00";
            case 5:
            case 6:
                return "#FF0000";
            case 7:
                return "#FFFF00";
            case 8:
                return "#FFFFFF";
            case 9:
                return "#CCCCCC";
            case 10:
            case 11:
                return "#00FF00";
            case 12:
                return "#080808";
            case 13:
            case 14:
                return "#FFFF00";
            case 15:
                return "#CCCCCC";
            case 16:
                return "#080808";
            default:
                return "#000000";
        }
    }


    private void initWebView(String htmlPath) {

        if(!isRequestStr(htmlPath))
            return;

        StringBuffer buffer = new StringBuffer();
        if(!htmlPath.contains("http://")){
            buffer.append("file://").append(htmlPath);
            htmlPath = buffer.toString();
        }else{
            buffer.append(ApplicationConfig.APP_OFFICE_HTMl).append(htmlPath);
            htmlPath = buffer.toString();
        }

        // step 1: Initialize sonic engine if necessary, or maybe u can do this when application created
        if (!SonicEngine.isGetInstanceAllowed()) {
            SonicEngine.createInstance(new SonicRuntimeImpl(getApplication()), new SonicConfig.Builder().build());
        }

        // step 2: Create SonicSession
        sonicSession = SonicEngine.getInstance().createSession(htmlPath,  new SonicSessionConfig.Builder().build());
        if (null != sonicSession) {
            sonicSession.bindClient(sonicSessionClient = new SonicSessionClientImpl());
        } else {
            throw new UnknownError("create session fail!");
        }

        //初始化布局
        WebSettings settings = web_view.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setSupportZoom(false);// 允许放大缩小
        settings.setBuiltInZoomControls(false);// 显示放大缩小按钮
        settings.setDisplayZoomControls(false);// api 11以上
        settings.setSupportMultipleWindows(true);
        settings.setGeolocationEnabled(true);// 启用地理定位
        settings.setTextZoom(100);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        web_view.setWebChromeClient(new WebChromeClient());
        web_view.setHorizontalScrollBarEnabled(false);
        web_view.setBackgroundColor(Color.TRANSPARENT); // 设置背景色

        if (sonicSessionClient != null) {
            sonicSessionClient.bindWebView(web_view);
            sonicSessionClient.clientReady();
        } else { // default mode
            web_view.loadUrl(htmlPath);
        }

        web_view.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //该方法在Build.VERSION_CODES.LOLLIPOP以前有效，从Build.VERSION_CODES.LOLLIPOP起，建议使用shouldOverrideUrlLoading(WebView, WebResourceRequest)} instead
                //返回false，意味着请求过程里，不管有多少次的跳转请求（即新的请求地址），均交给webView自己处理，这也是此方法的默认处理
                //返回true，说明你自己想根据url，做新的跳转，比如在判断url符合条件的情况下，我想让webView加载http://ask.csdn.net/questions/178242
                if(url.endsWith(".docx") ){
                    StringBuffer buffer = new StringBuffer(ApplicationConfig.APP_OFFICE_HTMl);
                    buffer.append(url);
                    Uri uri = Uri.parse(buffer.toString());
                    Intent intent = new Intent(Intent.ACTION_VIEW,uri);
                    startActivity(intent);
                }else{
                    view.loadUrl(url);
                }
                return true;
            }

            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                //返回false，意味着请求过程里，不管有多少次的跳转请求（即新的请求地址），均交给webView自己处理，这也是此方法的默认处理
                //返回true，说明你自己想根据url，做新的跳转，比如在判断url符合条件的情况下，我想让webView加载http://ask.csdn.net/questions/178242
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    String tempURL = request.getUrl().toString();
                    if(tempURL.endsWith(".docx") ){
                        StringBuffer buffer = new StringBuffer(ApplicationConfig.APP_OFFICE_HTMl);
                        buffer.append(tempURL);
                        Uri uri = Uri.parse(buffer.toString());
                        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                        startActivity(intent);
                    }else{
                        view.loadUrl(tempURL);
                    }
                    return true;
                }

                return false;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                //网页页面加载完毕


                if (sonicSession != null) {
                    sonicSession.getSessionClient().pageFinish(url);
                }
            }

            //下面的方法是Tencent - sonic
            @TargetApi(21)
            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                return shouldInterceptRequest(view, request.getUrl().toString());
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                if (sonicSession != null) {
                    //step 6: Call sessionClient.requestResource when host allow the application
                    // to return the local data .
                    return (WebResourceResponse) sonicSession.getSessionClient().requestResource(url);
                }
                return null;
            }
        });

    }

    @Event(value = {R.id.back})
    private void viewOnClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                if (web_view.canGoBack())
                    web_view.goBack();
                else
                    this.finish();
                break;
        }
    }

    @Override
    public void initViewHandler() {}

    //重写Activity的onKeyDown事件，判断当用户按下“返回”按钮，webview返回上一页
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && web_view.canGoBack()) {
            web_view.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    /**
     * 主要是把webview所持用的资源销毁，
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(null != web_view){
            web_view.setWebChromeClient(null);
            web_view.setWebViewClient(null);
            web_view.destroy();
            web_view = null;
        }

        if (null != sonicSession) {
            sonicSession.destroy();
            sonicSession = null;
        }
    }
}
